<div class="box-page-container">
  <div class="box-page-header">
    <div class="title">Редактирование фотоальбома</div>
    <div class="other-controls right">
    </div>
  </div>
  <div class="box-page-body">
    <div class="box-message" id="message" style="display: none"></div>
    <div class="form">
        <dt id="title-label"><label for="title" class="required">Заголовок:</label></dt>
        <dd id="title-element"><input type="text" name="title" id="title" value="<?php echo $this->album->title ?>"><p class="description"></p></dd>
		<dt id="title-label"><label for="description" class="required">Описание:</label></dt>
        <dd id="text-element"><textarea name="description" id="description" rows="3" cols="52"><?php echo $this->album->description ?></textarea></dd>
        <h3>Фотографии:</h3>
        <ul id="photo-list" style="display: block;">
		</ul>
        <dd><input name="fileToUpload[]" id="file_upload" class="MultiFile" type="file"/></dd>
    </div>
  </div>
  <div class="box-page-footer">
    <div class="box-controls">
      <div class="right">
       	<div class="btn"><button onclick="save(this); return false;" class="primary">Сохранить</button></div>
      </div>
      <div id="progress_ajax" class="progress ajax-preloader-base"></div>
      <div id="control_text" class="box-controls-text"></div>
      <div class="clear-fix"></div>
    </div>
  </div>
  <div class="clear-fix"></div>
</div>
<link rel="stylesheet" href="/css/jquery.cleditor.css" />
<link rel="stylesheet" type="text/css" href="/css/mediaelementplayer.css">
<link rel="stylesheet" type="text/css" href="/css/mejs-skins.css">
<style>
@import url(/css/uploadify.css);
@import url(/css/nivo-zoom.css);
.form input {
  width: 280px;
}

#photo-list li {
  margin: 10px 0px;
  padding: 0px 0px 5px;
  position: relative;
  border: 1px solid white;
  display: inline-block;
}

.photo_edit_thumb {
  width: 160px;
  text-align: center;
  float: left;
}

.photo_edit_data {
  display: inline-block;
  margin: 0 10px;
  width: 485px;
}

.photo_edit_caption {
  overflow: hidden;
  resize: none;
  height: 60px;
  width: 100%;
  margin-bottom: 5px;
}

.photo_edit_header {
  color: #36638E;
  font-weight: bold;
  margin-bottom: 7px;
  height: 13px;
}
</style>
<script src="/js/jquery/jquery.uploadify.js"></script>
<script src="/js/jquery/jquery.nivo.zoom.pack.js" type="text/javascript"></script>
<script>
var photos = <?php echo $this->photos ?>;
if (photos.length > 0) {
	$.each(photos, function() {
		addPhoto(this);
	});
}
$('#file_upload').uploadify({
	'formData': {'sid': '<?php echo $this->client->sid ?>'},
	'debug'	   : false,
	'buttonText': 'Выбрать файлы...',
	'removeCompleted': true,
	'fileSizeLimit' : '50MB',
	'fileTypeExts' : '*.gif; *.jpg; *.png; *.jpeg',
    'swf'      : '/js/jquery/uploadify/uploadify.swf',
    'uploader' : '/cp/attachments/upload.attachment',
    'onUploadSuccess' : function(file, data, response) {
        var r = $.parseJSON(data);
        if (typeof r.error == 'string') {
            alert(r.error);
            return false;
        }
        addPhoto(r);
    },
    'onUploadError' : function(file, errorCode, errorMsg, errorString) {
        alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
    }
});
$('.form #title').keyup(function(){
	var val = $(this).val();
	var message = '';
	if (!val) {
		message = '<span style="color: red;">Пожалуйста, укажите заголовок фотоальбома!</span>';
	}
	var regexp = /^[a-zа-я0-9_\s\:\;\"\'\,\?\!\(\)\+\*\=\-\.]*$/i;
	if (!regexp.test(val)) {
		message = '<span style="color: red;">Не верный формат заголовка фотоальбома!<p>Только английский, русский алфавиты, пробел, цифры и знаки "-", "_", ".", ":", ";", ",", "?", "!", "(", ")", "+", "*", "=".</p></span>';
	}
	$('#title-element .description').html(message);
});

$('#file_upload-button').css({
    'height': '20px',
    'line-height': '20px',
    'width': '90px'
});
function addPhoto(data) {
    html = '<li id="'+data.id+'">';
    html+= '<div class="photo_edit_thumb"><a href="' + data.url + '" target="_blank" class="nivoZoom"><img src="' + data.url + '" width="160"/>';
	html+= '<div class="nivoCaption"></div></a></div><div class="photo_edit_data"><div class="photo_edit_header">Описание</div>';
	html+= '<textarea class="photo_edit_caption">' + data.description + '</textarea><div class="photos_move_block"><div id="progress_ajax_photo" style="display: none; float: right;" class="progress ajax-preloader-base"></div>';
	html+= '<a href="#" style="float: right" onclick="deletePhoto(this, ' + data.id + '); return false;">Удалить</a></div>';
	html+= '</div><br class="clear-fix">';
    html+= '</li>';
    $('#photo-list').show().append(html);
}
function deletePhoto(el, id) {
	$(el).hide().parent().find('#progress_ajax_photo').show();
	$.getJSON('/cp/attachments/delete.attach', {'id': id}, function(response){
		if (typeof response.status == 'string' && response.status == 'ok') {
			$(el).parent().parent().parent().remove();
		}
	});
}
function save(el) {
    var msgBox = goog.dom.$('message');
    var title = $('.form #title').val();
    var description = $('.form #description').val();
    if (!title) {
    	$('.form #title').focus();
    }
    if (!title) {
    	msgBox.innerHTML = '<p>Заголовок - обязателен для заполнения.</p>';
		fx = new goog.fx.dom.FadeInAndShow(msgBox, 200);
		fx.play();
		return false;
    }
	if (msgBox.innerHTML != '') {
		fx = new goog.fx.dom.FadeOutAndHide(msgBox, 200);
		fx.play();
		msgBox.innerHTML = '';
	}
	var photoElements = $('#photo-list>li');
	var photos = [];
	if (photoElements.length > 0) {
    	photoElements.each(function(){
        	photos.push({
				'photo_id': $(this).attr('id'),
				'photo_description': $(this).find('.photo_edit_caption').val()
			});
        });
	}
	var data = {
		'id': window.location.search.replace('?id=', ''),
		'title': title,
		'description': description,
		'photos': photos
	};
	$('#progress_ajax').show();
	$('#control_text').hide();
	$(el).hide();
	$.ajax({
		"url": "/cp/photo.albums/edit.save",
		"type": "POST",
		"dataType": "json",
	    "data": data,
		"success": function(response) {
			$('#progress_ajax').hide();
			$(el).hide();
			$('.box-page-body').html('Фотоальбом <b>' + title + '</b> сохранен. <a href="/cp/photo.albums">Перейти к списку фотоальбомов</a>, <a href="/cp/photo.albums/create">Создать еще фотоальбом</a>');
		},
		"error": function(response) {
			$('#progress_ajax').hide();
			$(el).show();
			$('#control_text').html('Во время обработки запроса, возникли ошибки.').show();
			setTimeout(function(){
				$('#control_text').hide()
			}, 4000);
		}
	});
}
</script>